package com.cl.service.imp;

import com.cl.NotFoundExcepiton;
import com.cl.dao.TagReporistory;
import com.cl.po.Tag;
import com.cl.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Long
 * @Date:Created in 16:34 2018/7/4
 * @Description:
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    TagReporistory tagReporistory;

    @Override
    public Tag saveTag(Tag tag) {
        return tagReporistory.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagReporistory.getOne(id);
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag tag1 = tagReporistory.getOne(id);
        if (tag1 == null){
            throw new NotFoundExcepiton("无此标签");
        }else {
            BeanUtils.copyProperties(tag,tag1);
            return tagReporistory.save(tag1);
        }
    }



    @Override
    public Tag getTagByName(String name) {
        return tagReporistory.findByName(name);
    }

    @Override
    public void deleteTag(Long id) {
        Tag tag = tagReporistory.getOne(id);
        tagReporistory.delete(tag);
    }

    @Override
    public Page<Tag> getTagList(Pageable pageable) {
        return tagReporistory.findAll(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagReporistory.findAllById(convertToList(ids));
    }

    private List<Long> convertToList(String ids){
        List<Long> list = new ArrayList<>();
        if ("".equals(ids)&& ids!=null){
            String[] idarray = ids.split(",");
            for (int i=0;i<idarray.length;i++){
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    public List<Tag> listTag() {
        return tagReporistory.findAll();
    }
}
